package TCP.DoubleWay;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

class Send extends Thread
{
    private Socket socket;
    private Scanner scan;
    
    public Send (Socket socket, Scanner scan)
    {
        this.socket = socket;
        this.scan = scan;
    }
    
    private void sendMessage()
    {
        try(PrintWriter printWriter = new PrintWriter(socket.getOutputStream()))
        {
            while(true)
            {
                String str = scan.next();
                
                printWriter.println(str);
                printWriter.flush();
            }
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
    }
    
    @Override
    public void run ()
    {
        this.sendMessage();
    }
}

class Receive extends Thread
{
    private Socket socket;
    
    public Receive (Socket socket)
    {
        this.socket = socket;
    }
    
    private void getMessage()
    {
        try(BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream())))
        {
            while(true)
            {
                String str = bufferedReader.readLine();
                
                System.out.println("曰：" + str);
            }
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
    }
    
    @Override
    public void run ()
    {
        this.getMessage();
    }
}

class Server extends Thread
{

}

public class GoodTCP
{
    public static void main (String[] args) throws IOException
    {
        ServerSocket serverSocket = null;
        Socket socket = null;
        
        try
        {
            Scanner scan = new Scanner(System.in);
            System.out.println("请输入：server <port> 或：<ip> <port>");
            
            String str = scan.nextLine();
            String[] split = str.split(" ");
    
            if("server".equals(split[0]))
            {
                System.out.println("TCP服务端 监听 " + split[1] + "...");
                serverSocket = new ServerSocket(Integer.parseInt(split[1]));
                socket = serverSocket.accept();
            }
            else
            {
                socket = new Socket(split[0], Integer.parseInt(split[1]));
                System.out.println("客户端 连接成功!");
            }
            
            new Send(socket, scan).start();
            new Receive(socket).start();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            if(serverSocket != null)
                serverSocket.close();
        }
    }
}
